import json
import os

from flask import Blueprint, jsonify, request, url_for

from application import app, db
from common.models.wolf.AccessToken import AccessToken
from common.models.wolf.Room import Room
from common.models.wolf.User import User
import requests
from PIL import Image
from io import BytesIO

from datetime import datetime

route_wolf = Blueprint('wolf_page', __name__,static_folder="static")

@route_wolf.route("/create", methods=['POST', 'GET'])
def create():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    if request.method == 'GET':
        room_id = req['room_id'] if 'room_id' in req else ''
        room = Room.query.filter_by(room_id=room_id).first()
        if not room:
            resp['code'] = -1
            resp['msg'] = '房间参数错误'
            return jsonify(resp)

        resp['data'] = {'userList': room.user_list, 'numCurrent': room.current_num}
        return jsonify(resp)

    if request.method == 'POST':
        name = req['name'] if 'name' in req else ''
        code = req['code'] if 'code' in req else ''
        role_list = req['roleList'] if 'roleList' in req else ''
        avatarUrl = req['avatarUrl'] if 'avatarUrl' else ''

        if not role_list or len(role_list) < 5:
            resp['code'] = -1
            resp['msg'] = '人数不足，请重新选择'
            return jsonify(resp)

        if not name or not code:
            resp['code'] = -1
            resp['msg'] = '当前用户不存在'
            return jsonify(resp)

        tmp_user = User.query.filter_by(name=name).first()

        if not tmp_user:
            user = User(name=name, code=code, avatar=avatarUrl)
            db.session.add(user)
            db.session.commit()
            tmp_user = User.query.filter_by(id=user.id).first()

        if tmp_user:
            user_list = [tmp_user.to_dict()]
            room = Room()
            room.user_list = json.dumps(user_list)
            room.role_string = role_list
            room.current_num = 1
            db.session.add(room)
            db.session.commit()
            resp['data'] = {'roomId': room.room_id, 'userList': room.user_list, 'roleString': room.role_string}
        return jsonify(resp)


@route_wolf.route('/delete', methods=['GET'])
def delete():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    room_id = int(req['room_id']) if 'room_id' in req else 0
    if not room_id or room_id < 0:
        resp['code'] = -1
        resp['msg'] = '房间不存在'
        return jsonify(resp)

    Room.query.filter_by(room_id=room_id).delete()
    return jsonify(resp)


@route_wolf.route('/join', methods=['POST'])
def join():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}
    req = request.values

    room_id = int(req['room_id']) if 'room_id' in req else 0
    name = req['name'] if 'name' in req else ''
    code = req['code'] if 'code' in req else ''
    avatarUrl = req['avatarUrl'] if 'avatarUrl' in req else ''

    # 房间号错误
    if not room_id or room_id < 0:
        resp['code'] = 100
        resp['msg'] = '请输入正确的房间号码'
        return jsonify(resp)

    room = Room.query.filter_by(room_id=room_id).first()

    # 假如房间不存在
    if not room:
        resp['code'] = 100
        resp['msg'] = '房间不存在或已关闭'
        return jsonify(resp)

    user_list = json.loads(room.user_list)
    for i in user_list:
        # 该用户已存在房间中
        if name == i['name']:
            resp['msg'] = '角色已在房间'
            resp['data'] = {'roomId': room.room_id, 'userList': room.user_list, 'roleString': room.role_string, 'numCurrent': room.current_num}
            return jsonify(resp)

    user = User(name=name, code=code, avatar=avatarUrl)
    db.session.add(user)
    db.session.commit()

    # 新增用户到房间用户列表
    user_list.append(user.to_dict())
    room.user_list = json.dumps(user_list)
    room.current_num += 1
    db.session.commit()

    resp['data'] = {'roomId': room.room_id, 'userList': room.user_list, 'roleString': room.role_string,
                    'numCurrent': room.current_num}
    return jsonify(resp)


@route_wolf.route('/index', methods=['GET'])
def index():
    resp = {'msg': "test ok"}
    return jsonify(resp)


@route_wolf.route('/test', methods=['GET'])
def get_room_QRCode():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}

    req = request.values

    room_id = req['room_id'] if 'room_id' in req else ''
    QRCode_filename = room_id+".jpg"
    QRCode_dir = "./static/room_QRCode/"+QRCode_filename

    # 如果存在
    if os.path.exists(QRCode_dir):
        # TODO 前端扫码 接受未完成
        # QRCode_url = url_for('.static', filename=QRCode_dir)
        QRCode_url = url_for('static', _external=True,filename= "room_QRCode/"+QRCode_filename)
        resp['data'] = {'QRCodeUrl': QRCode_url}
        return jsonify(resp)

    # 如果不存在则 使用API获取
    access_token = get_access_token()
    url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='+ access_token

    # 从微信获取房间QRCode
    page = 'pages/role/role'
    json_data = {"scene": room_id,
                 "page": page,
                 }
    try:
        # 成功返回二进制流图片 失败返回json对象
        r = requests.post(url, json=json_data)

        # 储存图片
        if type(r.content) is bytes:
            i = Image.open(BytesIO(r.content))
            i.save(QRCode_dir, 'jpeg')
            resp['data'] = {'QRCodeDir': QRCode_dir}
            return jsonify(resp)
        else:
            response_dict = r.json()
            if 'errcode' in response_dict.keys():
                resp['code'] = -1
                resp['msg'] = 'getwxacodeunlimit接口失败 WX:' + response_dict['errmsg']
                return jsonify(resp)

    except requests.HTTPError:
        resp['code'] = -1
        resp['msg'] = 'getwxacodeunlimit接口 请求异常'
        return jsonify(resp)


def get_access_token():

    now = int(datetime.now().timestamp())

    # 用主键查询
    access_token = AccessToken.query.get(1)

    if int(access_token.expire_time) >= now:
        update_access_token()
        access_token = AccessToken.query.get(1)

    return access_token.token


def update_access_token():
    resp = {'code': 200, 'msg': '操作成功', 'data': {}}

    # TODO 后续改成配置
    app_id = 'wx10918652ceda6ef0'
    app_secret = 'e0de16308215602a2397aaf2d844630d'
    get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(app_id,app_secret)

    try:
        r = requests.get(get_token_url)
        response_dict = r.json()

        # if response_dict.has_key('errcode'):
        if 'errcode' in response_dict.keys():
            resp['code'] = -1
            resp['msg'] = '获取access_token失败 WX:' + response_dict['errmsg']
            return jsonify(resp)

        ## {"access_token":"ACCESS_TOKEN","expires_in":7200}
        token = response_dict['access_token']

        # 过期时间戳
        now = int(datetime.now().timestamp())
        expire_time = now + response_dict['expires_in']

        # 查询修改提交
        access_token = AccessToken.query.get(1)
        access_token.token = token
        access_token.expire_time = expire_time
        db.session.commit()

    except requests.HTTPError:
        resp['code'] = -1
        resp['msg'] = '获取access_token接口 请求异常'
        return jsonify(resp)





